package cn.ai.boot.config;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class PCFUtils {
    
    /**
     * 读取PCF文件内容
     * @param filePath 文件路径
     * @return 文件内容字符串
     * @throws IOException 文件读取异常
     */
    public static String readPCFFile(String filePath) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
    }

    /**
     * 替换PCF文件中的内容
     * @param filePath 文件路径
     * @param oldStr 需要替换的字符串
     * @param newStr 替换后的字符串
     * @throws IOException 文件操作异常
     */
    public static void replacePCFContent(String filePath, String oldStr, String newStr) throws IOException {
        String content = readPCFFile(filePath);
        content = content.replace(oldStr, newStr);
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8))) {
            writer.write(content);
        }
    }

    /**
     * 使用正则表达式替换PCF文件内容
     * @param filePath 文件路径
     * @param regex 正则表达式
     * @param replacement 替换字符串
     * @throws IOException 文件操作异常
     */
    public static void regexReplacePCFContent(String filePath, String regex, String replacement) throws IOException {
        String content = readPCFFile(filePath);
        content = content.replaceAll(regex, replacement);
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8))) {
            writer.write(content);
        }
    }
}
